<template>
  <PageWrapper class="high-form" title="测试页面">
    <CollapseContainer title="基础信息">
      <BasicForm @register="registerForm" ref="formRef">
        <template #localSearch="{ model, field }">
          <ApiSelect :api="getAllClient" showSearch v-model:value="model[field]" optionFilterProp="label"
            resultField="data" labelField="name" valueField="id" />
        </template>
        <template #selectDept="{ model, field }">
          <Tag color="green" v-for="tag in model['deptNameList']" v-if="model[field]" closable @close="handleDeleteOrg">
            {{ tag }}
          </Tag>
          <Button @click="handleSelectOrg">+</Button>
        </template>
        <template #selectStaff="{ model, field }">
          <Tag color="green" v-if="model[field]" closable @close="handleDeleteManager1">
            {{ model['selectStaffName'] }}
          </Tag>
          <Button @click="handleSelectManager1">+</Button>
        </template>

        <template #detailList="{ model }">
          <BasicTable @register="registerTable" :dataSource="model.detailList">
            <template #toolbar>
              <a-button type="primary" @click="handleCreate"> 新增</a-button>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction :actions="createActions(record)" />
              </template>
            </template>
          </BasicTable>
        </template>
      </BasicForm>
    </CollapseContainer>
    <OrgSelector @register="registerOrgModal" @success="handleSelectOrgSuccess" />
    <StaffSelector @register="registerManager1Modal" @success="handleSelectManager1Success" />

    <CollapseContainer title="流程信息">
      <SelectApprover :id="id" :type="type" @success="getFlowData" />
    </CollapseContainer>

    <a-button type="primary" @click="handleSubmitForm" v-if="serverData.showCommit"> 提交 </a-button> <span> </span>
    <a-button type="primary" @click="handleSaveForm(0)" v-if="serverData.showCommit"> 存草稿 </a-button>

  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, } from 'vue';
import { Button, Tag } from 'ant-design-vue';
import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
import { PageWrapper } from '/@/components/Page';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';
import { useRouter } from 'vue-router'
import { useModal } from '/@/components/Modal';
import { cloneDeep } from 'lodash-es';
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem, } from '/@/components/Table';

import { formSchema } from './data';
import { add, update } from '/@/api/project/plan';
import OrgSelector from '/@/views/components/selector/orgSelector/index.vue';
import StaffSelector from '/@/views/components/selector/staffSelector/index.vue';
import SelectApprover from '/@/views/process/SelectApprover.vue';
import { businessdata } from '/@/api/work/work';
import { getList } from '/@/api/base/dictionary';
import { getAll as getAllClient } from '/@/api/business/client';


export default defineComponent({
  components: {
    BasicTable, TableAction, BasicForm, CollapseContainer, PageWrapper, Button, Tag,
    ApiSelect, OrgSelector, StaffSelector, SelectApprover,
  },
  emits: ['success', 'register'],
  setup() {
    //主表单
    const [registerForm, { setFieldsValue, validate }] = useForm({
      schemas: formSchema,
      labelWidth: 100,
      showActionButtonGroup: false,
    });

    //流程参数 begin
    const serverDataType: any = { showApprove: false, aaList: [], ccList: [] }
    const serverData = ref(serverDataType);
    const id = ref(1);
    const type = ref('CheckPlan');
    function getFlowData(returnData: any) {
      serverData.value = returnData
    }
    //流程参数 end

    onMounted(() => {
      if (id.value > 0) {
        setFieldsValue(serverData)
        businessdata({ id: id.value, type: type.value }).then(res => {
          res.projectType = res.projectType.split(',')
          setFieldsValue(res)
          console.log('获取【采样计划】数据成功', res)
        })
      }
    })

    //列表
    const [registerTable, { getDataSource, insertTableDataRecord, deleteTableDataRecord, }] = useTable({
      columns: [{
        title: '检测类别',
        dataIndex: 'checkType',
        editRow: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          api: getList,
          labelField: 'value',
          valueField: 'value',
          params: '检测类别',
        },
      }, {
        title: '检测点位',
        dataIndex: 'checkSpot',
        editRow: true,
      }, {
        title: '项目',
        dataIndex: 'checkItem',
        editRow: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          api: getList,
          labelField: 'value',
          valueField: 'value',
          params: '水（含大气降水）和废水',
        },
      }, {
        title: '点位(个)',
        dataIndex: 'checkSpotCount',
        editRow: true,
      }, {
        title: '频次(次)',
        dataIndex: 'checkFreq',
        editRow: true,
      }, {
        title: '周期(天)',
        dataIndex: 'checkCycle',
        editRow: true,
      }, {
        title: '评价标准',
        dataIndex: 'checkStandard',
        editRow: true,
      }, {
        title: '采样时间',
        dataIndex: 'checkTime',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          valueFormat: 'YYYY-MM-DD',
          format: 'YYYY-MM-DD',
        },
      },],
      formConfig: {
        labelWidth: 120,
        showAdvancedButton: false,
        showResetButton: false,
        autoSubmitOnEnter: true,
      },
      canColDrag: true,
      useSearchForm: false,
      bordered: true,
      showIndexColumn: false,
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        fixed: false,
      },
    });
    //列表操作栏定义
    function createActions(record: EditRecordRow): ActionItem[] {
      if (!record.editable) {
        return [
          {
            tooltip: '复制',
            icon: 'ant-design:copy-outlined',
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
            onClick: handleCopy.bind(null, record),
          },
          {
            tooltip: '编辑',
            icon: 'clarity:note-edit-line',
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
            onClick: handleEdit.bind(null, record),
          },
          {
            tooltip: '删除',
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
              placement: 'left'
            },
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave.bind(null, record),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel.bind(null, record),
          },
        },
      ];
    }


    function handleCreate() {
      let item = { checkType: '', checkTime: '' }
      insertTableDataRecord(item)
    }

    function handleCopy(record: EditRecordRow) {
      const data = cloneDeep(record.editValueRefs) || {};
      insertTableDataRecord(data)
    }

    const currentEditKeyRef = ref('');

    function handleEdit(record: EditRecordRow) {
      currentEditKeyRef.value = record.key;
      record.onEdit?.(true);
    }

    function handleCancel(record: EditRecordRow) {
      currentEditKeyRef.value = '';
      record.onEdit?.(false, false);
    }

    function handleDelete(record: EditRecordRow) {
      deleteTableDataRecord(record.id)
    }

    const { createMessage } = useMessage();

    async function handleSave(record: EditRecordRow) {
      // 校验
      createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();
      if (valid) {
        try {
          const data = cloneDeep(record.editValueRefs);
          console.log(data);
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }





    const router = useRouter();
    //提交，需要选择审批人
    async function handleSubmitForm() {
      if (serverData.value.aaList == null || serverData.value.aaList.length == 0) {
        createMessage.success({
          content: '请选择审批人',
          duration: 1,
        });
        return
      }
      handleSaveForm(1)
      router.push('/work/work-done');//跳转已处理
    }
    async function handleSaveForm(type) {
      let content = '存草稿成功'
      const values = await validate();
      if (type === 1) {
        content = '提交成功'
        values['aaList'] = serverData.value.aaList
        values['ccList'] = serverData.value.ccList
      }
      let tableData = getDataSource()
      values.detailList = tableData
      console.log('formData=', values)
      values.projectType = values.projectType.join(',')

      if (id.value > 0) {
        await update(values);
      } else {
        await add(values).then(res => {
          //跳转查看页
          router.push('/project/plan/view/' + res.id);
        });
      }
      createMessage.success({
        content: content,
        duration: 1,
      });
    }

    //选部门begin
    //选中的部门
    const selectedOrgList = ref([]);
    const [registerOrgModal, { openModal: openOrgSelector, setModalProps: setOrgModalProps }] = useModal();
    // 弹出选择部门
    function handleSelectOrg() {
      openOrgSelector(true, {
        selectorProps: {
          multiSelect: true,
          selectedList: selectedOrgList.value,
        }
      });
      setOrgModalProps({
        title: `选择部门`,
        bodyStyle: { padding: '0px', margin: '0px' },
        width: 850, height: 450,
        showOkBtn: true, showCancelBtn: false
      });
    }
    // 选择部门成功回调
    async function handleSelectOrgSuccess(selectedList: any) {
      if (selectedList && selectedList.length > 0) {
        var deptNameList = []
        var idList = []
        selectedList.forEach((item) => {
          idList.push(item.id);
          deptNameList.push(item.name);
        });

        setFieldsValue({
          deptId: idList.join(','),
          deptNameList: deptNameList,
        });
        console.log('handleSelectOrgSuccess 成功回调：', idList.join(','), deptNameList)
      }
    }
    // 删除选择审批人成功回调
    async function handleDeleteOrg() {
      selectedOrgList.value = [];
    }
    //选部门end

    //选人begin
    const selectedList1 = ref([]);

    const [registerManager1Modal, { openModal: openPersonalSelector1, setModalProps: setPersonalModalProps1 }] = useModal();
    function handleSelectManager1() {
      openPersonalSelector1(true, {
        selectorProps: {
          multiSelect: false,
          selectedList: selectedList1.value,
        }
      });
      setPersonalModalProps1({
        title: `选择员工`,
        bodyStyle: { padding: '0px', margin: '0px' },
        width: 850, height: 450,
        showOkBtn: true, showCancelBtn: false
      });
    }
    async function handleSelectManager1Success(selectedList: any) {
      selectedList1.value = selectedList.map(item => { return { uid: item.uid, code: item.code, name: item.name } });
      if (selectedList && selectedList.length > 0) {
        console.log('选择成功回调：', selectedList1.value)
        setFieldsValue({
          'selectStaff': selectedList[0].code,
          'selectStaffName': selectedList[0].name
        })
      }
    }
    async function handleDeleteManager1() {
      setFieldsValue({
        'selectStaff': [],
      });
      selectedList1.value = [];
    }
    //选人end


    return {
      registerForm, handleSaveForm, handleSubmitForm, getAllClient,
      registerOrgModal, handleSelectOrg, handleSelectOrgSuccess, handleDeleteOrg,
      registerManager1Modal, handleSelectManager1, handleSelectManager1Success, handleDeleteManager1,
      registerTable, handleCreate, handleEdit, handleDelete, handleSave, createActions,
      getFlowData, serverData, id, type
    };
  },
});
</script>
